<template>
  <div class="admin-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="searchParams.name" placeholder="请输入图片名称" clearable @keyup.enter.native="searchByName">
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" @click="searchByName">搜索图片名称</el-button>
          <el-button type="success" @click="showAddDialog">新增</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 信息展示区 -->
    <div class="table-container">
      <el-table :data="tableData" style="width: 100%" border v-if="tableData.length > 0">
        <el-table-column prop="id" label="ID" width="180">
        </el-table-column>
        <el-table-column prop="name" label="图片名称">
        </el-table-column>
        <el-table-column label="轮播图图片">
          <template slot-scope="scope">
            <el-image style="width: 100px; height: 100px;" :src="scope.row.image_url" fit="cover"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间">
          <template slot-scope="scope">
            {{ formatDate(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="update_time" label="更新时间">
          <template slot-scope="scope">
            {{ formatDate(scope.row.update_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-else class="no-data">
        <p>没有找到匹配的数据</p>
      </div>
    </div>
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="currentPage" :page-size.sync="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="allData.length">
      </el-pagination>
    </div>
    <!-- 编辑对话框 -->
    <el-dialog title="编辑轮播图" :visible.sync="editDialogVisible" width="30%">
      <el-form :model="currentRow" :rules="editRules" ref="editForm">
        <el-form-item label="图片名称" prop="name">
          <el-input v-model="currentRow.name"></el-input>
        </el-form-item>
        <el-form-item label="轮播图图片" prop="image_url">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8887/upload"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
            :http-request="customUpload">
            <el-image v-if="currentRow.image_url" :src="currentRow.image_url" class="avatar"></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdate">更新</el-button>
      </span>
    </el-dialog>
    <!-- 新增对话框 -->
    <el-dialog title="新增轮播图" :visible.sync="addDialogVisible" width="30%">
      <el-form :model="addCarousel" :rules="addRules" ref="addForm">
        <el-form-item label="图片名称" prop="name">
          <el-input v-model="addCarousel.name"></el-input>
        </el-form-item>
        <el-form-item label="轮播图图片" prop="image_url">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8887/upload"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
            :http-request="customUpload">
            <el-image v-if="addCarousel.image_url" :src="addCarousel.image_url" class="avatar"></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAdd">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import axios from 'axios';
import {
  Input,
  Row,
  Col,
  Button,
  Table,
  TableColumn,
  Dialog,
  Form,
  FormItem,
  Pagination,
  Message,
  Image as ElImage,
  Upload
} from 'element-ui';

export default {
  name: 'CarouselTable',
  components: {
    'el-input': Input,
    'el-row': Row,
    'el-col': Col,
    'el-button': Button,
    'el-table': Table,
    'el-table-column': TableColumn,
    'el-dialog': Dialog,
    'el-form': Form,
    'el-form-item': FormItem,
    'el-pagination': Pagination,
    'el-image': ElImage,
    'el-upload': Upload
  },
  data() {
    return {
      allData: [], // 存储所有数据
      tableData: [], // 存储当前页的数据
      searchParams: {
        name: ''
      },
      editDialogVisible: false,
      currentRow: {
        id: null,
        image_url: '',
        name: ''
      },
      addDialogVisible: false,
      addCarousel: {
        image_url: '',
        name: ''
      },
      editRules: {
        image_url: [{
          required: true,
          message: '请输入图片URL',
          trigger: 'blur'
        }],
        name: [{
          required: true,
          message: '请输入图片名称',
          trigger: 'blur'
        }]
      },
      addRules: {
        image_url: [{
          required: true,
          message: '请输入图片URL',
          trigger: 'blur'
        }],
        name: [{
          required: true,
          message: '请输入图片名称',
          trigger: 'blur'
        }]
      },
      currentPage: 1,
      pageSize: 10,
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      const token = localStorage.getItem('Authorization');
      if (!token) {
        this.$message.error('未授权访问');
        return;
      }
      const headers = {
        'Content-Type': 'application/json',
        'Authorization': token
      };
      axios.get('http://localhost:8887/homecarousel/findAll', {
          headers
        })
        .then(response => {
          if (response.data.code === 200) {
            this.allData = response.data.data;
            this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this
              .currentPage * this.pageSize);
          } else {
            this.$message.error('获取数据失败: ' + response.data.message);
          }
        })
        .catch(error => {
          console.error('请求失败:', error);
          if (error.response && error.response.status === 401) {
            this.$message.error('授权失败，请重新登录');
          } else {
            this.$message.error('请求失败，请检查网络或联系管理员');
          }
        });
    },
    formatDate(value) {
      const date = new Date(value);
      return new Intl.DateTimeFormat('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).format(date);
    },
    searchByName() {
      const token = localStorage.getItem('Authorization');
      const headers = {
        'Content-Type': 'application/json',
        'Authorization': token
      };
      axios.get('http://localhost:8887/homecarousel/selectname', {
headers,
params: {
name: this.searchParams.name
}
})
.then(response => {
if (response.data.code === 200 && response.data.data.length > 0) {
this.allData = response.data.data;
this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this
.currentPage * this.pageSize);
this.currentPage = 1; // 重置当前页为 1
} else {
this.$message.error(response.data.message || '未找到匹配的轮播图');
this.tableData = []; // 清空表格数据
}
})
.catch(error => {
console.error('请求失败:', error);
if (error.response && error.response.status === 401) {
this.$message.error('授权失败，请重新登录');
} else {
this.$message.error('请求失败，请检查网络或联系管理员');
}
});
},
handleEdit(row) {
if (row) {
this.currentRow = {
...row
};
this.editDialogVisible = true;
} else {
console.error('Error: Row data is null');
}
},
handleUpdate() {
this.$refs.editForm.validate((valid) => {
if (valid) {
const token = localStorage.getItem('Authorization');
const headers = {
'Content-Type': 'application/json',
'Authorization': token
};
axios.post('http://localhost:8887/homecarousel/updateHomecarouselById', this.currentRow, {
headers
})
.then(response => {
if (response.data.code === 200) {
this.$message.success('更新成功');
this.editDialogVisible = false;
this.fetchData();
} else {
this.$message.error('更新失败: ' + response.data.message);
}
})
.catch(error => {
console.error('请求失败:', error);
if (error.response && error.response.status === 401) {
this.$message.error('授权失败，请重新登录');
} else {
this.$message.error('请求失败，请检查网络或联系管理员');
}
});
} else {
this.$message.error('表单验证失败');
}
});
},
handleDelete(id) {
this.$confirm('确认删除这条记录吗?', '提示', {
type: 'warning'
}).then(() => {
const token = localStorage.getItem('Authorization');
const headers = {
'Content-Type': 'application/json',
'Authorization': token
};
axios.post('http://localhost:8887/homecarousel/deleteHomecarouselById?id=' + id, {}, { headers })
.then(response => {
if (response.data.code === 200) {
this.$message.success('删除成功');
this.fetchData(); // 重新加载数据
} else {
this.$message.error('删除失败: ' + response.data.message);
}
})
.catch(error => {
console.error('请求失败:', error);
if (error.response && error.response.status === 401) {
this.$message.error('授权失败，请重新登录');
} else if (error.response && error.response.status === 400) {
this.$message.error('请求参数错误，请检查参数后重试');
} else {
this.$message.error('请求失败，请检查网络或联系管理员');
}
});
}).catch(() => {
this.$message.info('已取消删除');
});
},
showAddDialog() {
this.addDialogVisible = true;
this.addCarousel = {
image_url: '',
name: ''
};
},
handleAdd() {
this.$refs.addForm.validate((valid) => {
if (valid) {
const token = localStorage.getItem('Authorization');
const headers = {
'Content-Type': 'application/json',
'Authorization': token
};
axios.post('http://localhost:8887/homecarousel/addHomecarousel', this.addCarousel, {
headers
})
.then(response => {
if (response.data.code === 200) {
this.$message.success('新增成功');
this.addDialogVisible = false;
this.fetchData();
} else {
this.$message.error('新增失败: ' + response.data.message);
}
})
.catch(error => {
console.error('请求失败:', error);
if (error.response && error.response.status === 401) {
this.$message.error('授权失败，请重新登录');
} else {
this.$message.error('请求失败，请检查网络或联系管理员');
}
});
} else {
this.$message.error('表单验证失败');
}
});
},
handleSizeChange(newSize) {
this.pageSize = newSize;
this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
},
handleCurrentChange(newPage) {
this.currentPage = newPage;
this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
},
beforeImageUpload(file) {
const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
},
customUpload(file) {
const formData = new FormData();
formData.append('file', file.file);
axios.post('http://localhost:8887/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
if (response.data.code === 200) {
this.handleImageSuccess(response.data.data);
} else {
this.$message.error('上传失败: ' + response.data.message);
}
}).catch(error => {
console.error('请求失败:', error);
this.$message.error('请求失败，请检查网络或联系管理员');
});
},
handleImageSuccess(imageUrl) {
if (this.addDialogVisible) {
this.addCarousel.image_url = imageUrl;
} else {
this.currentRow.image_url = imageUrl;
}
}
}
};
</script>
<style scoped>
.admin-container {
  padding: 20px;
  max-width: 100%;
  overflow-x: auto;
}

.search-bar {
  margin-bottom: 20px;
}

.search-bar .el-row {
  justify-content: space-between;
}

.search-bar .el-button {
  margin-left: 10px;
}

.table-container {
  margin-top: 20px;
  overflow-x: auto;
}

.no-data {
  text-align: center;
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: left;
}

.dialog-footer {
  text-align: right;
}

.el-dialog__body {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  font-weight: bold;
}

.el-button--primary {
  background-color: #13ce66;
  border-color: #13ce66;
}

.el-button--primary:hover {
  background-color: #11b55e;
  border-color: #11b55e;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>